//
//  BrandListVC.m
//  ZPSALE
//
//  Created by fei on 14-8-12.
//  Copyright (c) 2014年 self. All rights reserved.
//

#import "BrandListVC.h"
#import "BrandListCell.h"
#import "MemberCenterViewController.h"
#import "CartViewController.h"
#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "ZPBrandDetailVC.h"
#import "JSBadgeView.h"
#import "logOnViewController.h"
#define Delay_Time 0.8
@interface BrandListVC ()
{
    JSBadgeView *numOfPackView;
    BOOL firstLoading;
}
@end

@implementation BrandListVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated {
    [self requestDataFromNet];
    [self getNumberOfProductInShopBag];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    [self setMemberVariable];
    
    [self setCollectionViewRefreshAndLoadMoreView];
    [self setNavigationItem];
    
    //checkLogin
    [[NSNotificationCenter defaultCenter] postNotificationName:StringForCheckLogin object:nil];
}

-(void)setMemberVariable{
    isRefresh = YES;
    isLoadingMore = NO;
    firstLoading = YES;
    brandListArray = [[NSMutableArray alloc] initWithCapacity:0];
    self.view.backgroundColor = ColorFromRGB(0xEEEEEE);
    currentPage = 1;
    totalPage = 1;
    perpageCount = 10;
    _countDownView.showImage = YES;
    _countDownView.viewAligment = CountDownViewAligment_left;
    _countDownView.labelFont = [UIFont systemFontOfSize:12];
    _countDownView.imageName = @"list_clock";
    _countDownView.backgroundColor = [UIColor clearColor];
    _countDownView.labelTextColor = [UIColor darkGrayColor];
    
    _bottomView.clipsToBounds = YES;
    _bottomView.layer.cornerRadius = 2.0f;
    
    numOfPackView = [[JSBadgeView alloc] initWithParentView:_toPacketButton alignment:JSBadgeViewAlignmentOnImage];
    numOfPackView.clipsToBounds = YES;
    numOfPackView.userInteractionEnabled = NO;
    numOfPackView.backgroundColor = [UIColor clearColor];
    numOfPackView.hidden = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark subViews

-(void)setNavigationItem {
    
    UIButton *homeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    homeBtn.frame = CGRectMake(0, 0, 44, 44);
    homeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 20, 0, -10);
    [homeBtn setImage:[UIImage imageNamed:@"home_page"] forState:UIControlStateNormal];
    [homeBtn addTarget:self action:@selector(rightBarbuttonItemClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    label.text = _titleString;
    label.font = [UIFont systemFontOfSize:16];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor darkGrayColor];
    self.navigationItem.titleView = label;
    
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
}

-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)setCollectionViewRefreshAndLoadMoreView {
//    footerView = [[EGORefreshTableFooterView alloc] initWithFrame:CGRectZero];
//    footerView.delegate = self;
//    [_productListCollectionView addSubview:footerView];
//    [self setRefreshFooterViewFrame];
    
    headerView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, -_productListCollectionView.frame.size.height, _productListCollectionView.frame.size.width, _productListCollectionView.frame.size.height)];
    headerView.delegate = self;
    [_productListCollectionView addSubview:headerView];
}

-(void)setRefreshFooterViewFrame {
    float hei = MAX(_productListCollectionView.bounds.size.height, _productListCollectionView.contentSize.height);
    footerView.frame = CGRectMake(0, hei, _productListCollectionView.frame.size.width, _productListCollectionView.bounds.size.height);
}

#pragma mark datas
-(void)requestDataFromNet {
    
    MBProgressHUD *requestHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    if (firstLoading) {
        requestHUD.hidden = NO;
        firstLoading = NO;
    }
    if (isRefresh) {
        currentPage = 1;
        [brandListArray removeAllObjects];
    } else {
        if (currentPage < totalPage) {
            currentPage += 1;
        } else {
//            [footerView egoRefreshScrollViewDataSourceDidFinishedLoading:_productListCollectionView];
            if (isLoadingMore) {
                requestHUD.hidden = NO;
                requestHUD.mode = MBProgressHUDModeText;
                requestHUD.labelText = @"已加载完所有相关商品";
                [requestHUD hide:YES afterDelay:Delay_Time];
            } else
                requestHUD.hidden = YES;
            isLoadingMore = NO;
            
            return ;
        }
    }
    

//    NSDictionary *requestParameterDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",currentPage],@"pagenumber",[NSString stringWithFormat:@"%d",perpageCount],@"pagesize",_specialId,@"url_id",@"1",@"sort", nil];
     _sortString = @"4";
    NSDictionary *requestParameterDict = [NSDictionary dictionaryWithObjectsAndKeys:_specialId,@"url_id",_sortString,@"sort", nil];
   
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    [httpManager GET:APIURL"sale/ProductsList.json" parameters:requestParameterDict success:^(AFHTTPRequestOperation *operation,id resultObject) {
        NSArray *resultArray = resultObject[@"content"];
        for (NSDictionary *dict in resultArray) {
            if (dict[@"outlets_item_infos"]) { //列表信息
                for (NSDictionary *itemDict in dict[@"outlets_item_infos"]) {
                    if (isRefresh) {
                        [brandListArray removeAllObjects];
                        
                        [headerView egoRefreshScrollViewDataSourceDidFinishedLoading:_productListCollectionView];
                        isRefresh = NO;
                    }
                    if (![dict isEqual:[NSNull null]] && [dict count] > 0) {
                        [brandListArray addObject:itemDict];
                    }
                }
            }
            if (dict[@"outlets_info"]) { //特卖时间数据
                NSDictionary *timeDict = dict[@"outlets_info"];
                [_countDownView setTimeWithTimeIntervalString:[NSString stringWithFormat:@"%@",timeDict[@"EndTime"]] andType:CountDownView_CountDown];
                listID = [NSString stringWithFormat:@"%d",[timeDict[@"list_id"] intValue]];
            }
        }
        
        requestHUD.mode = MBProgressHUDModeText;
        [requestHUD hide:YES afterDelay:.2];
        
//        else {
//            [footerView egoRefreshScrollViewDataSourceDidFinishedLoading:_productListCollectionView];
//            isLoadingMore = NO;
//            
//        }
        [_productListCollectionView reloadData];
        
    }failure:^(AFHTTPRequestOperation *operation ,NSError *error) {
        requestHUD.mode = MBProgressHUDModeText;
        requestHUD.labelText = @"加载失败,请稍后再试.";
        [requestHUD hide:YES afterDelay:Delay_Time];
    }];

}
//取专题 时间 及 图片
-(void)requestProductsListHeadImage {
    
    
    
}

-(void)getNumberOfProductInShopBag {
    NSDictionary *paraDict;
    
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    NSString *memeberId = [dataDic valueForKey:@"memberId"];
    NSString *atoken = [dataDic valueForKey:@"token"];
    //不需要验证token，保证该memberId获取过token即可
    if ([memeberId length] == 0 ||[memeberId isEqual:[NSNull null]] ||[atoken isEqual:[NSNull null]] ||[atoken length] == 0) {
        

    } else {
        paraDict = @{
                     @"memberid":memeberId
                     };
        AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
        
        [httpManager GET:APIURL"sale/getCartProductNum.json" parameters:paraDict success:^(AFHTTPRequestOperation *operation ,id resultObject){
            int  numOfProduct = [resultObject[@"cartNum"] intValue];
            if (numOfProduct == 0) {
                numOfPackView.badgeText = @"0";
                numOfPackView.hidden = YES;
            } else {
                numOfPackView.badgeText = [NSString stringWithFormat:@"%d",numOfProduct];
                numOfPackView.hidden = NO;
            }
        } failure:^(AFHTTPRequestOperation *operation,NSError *error) {
            numOfPackView.badgeText = @"0";
            numOfPackView.hidden = YES;
        }];
    }
    
}

-(void)refreshOrLoadMoreNumber {
    
}

#pragma mark UICollectionView DataSource 
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [brandListArray count];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//    [self setRefreshFooterViewFrame];
    BrandListCell *cell = (BrandListCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"brandListCell" forIndexPath:indexPath];
    cell.layer.cornerRadius = 4.0f;
    cell.clipsToBounds = YES;
    cell.layer.borderWidth = 1.0f;
    cell.layer.borderColor = ColorFromRGB(0xE0E0E0).CGColor;
    cell.backgroundColor = [UIColor whiteColor];
    if (brandListArray.count > indexPath.row) {
        NSDictionary *itemDict = [brandListArray objectAtIndex:indexPath.row];
        [cell.brandImageView sd_setImageWithURL:Return_imageUrl(itemDict[@"sourceImage"], 450)  placeholderImage:[UIImage imageNamed:@"brandlist_noimage"] options:SDWebImageRetryFailed];
        cell.brandNameLabel.text = [itemDict objectForKey:@"brandName"];
        NSString *zpPrice = [NSString stringWithFormat:@"%d",[[itemDict objectForKey:@"price"] intValue]];
        NSString *markPrice = [NSString stringWithFormat:@"%d",[[itemDict objectForKey:@"marketPrice"] intValue]];
        cell.brandSalePriceLabel.attributedText = [self returnAttStringWithNewPrice:zpPrice andMarketPrice:markPrice];
        cell.brandDiscountLabel.text = [NSString stringWithFormat:@"%.1f折",(float)[zpPrice intValue]/[markPrice intValue]*10];
        if ([itemDict[@"stock"] intValue] < 1) {
            cell.saleOverImageView.hidden = NO;
            
        } else {
            cell.saleOverImageView.hidden = YES;
        }
    }
   
    
    return cell;
}

-(NSMutableAttributedString *)returnAttStringWithNewPrice:(NSString *)newS andMarketPrice:(NSString *)marketS {
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"¥%@ ¥%@",newS,marketS]];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, newS.length+1)];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(newS.length+2, marketS.length+1)];
    [string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:9] range:NSMakeRange(0, 1)];
    [string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:14] range:NSMakeRange(1, newS.length)];
    [string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:9] range:NSMakeRange(newS.length+2, 1)];
    [string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:12] range:NSMakeRange(newS.length+3, marketS.length)];
    
    return string;
}
#pragma mark UICollectionView delegate
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 6.5, 0, 6.5);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *itemDict = [brandListArray objectAtIndex:indexPath.row];
    
    if ([itemDict[@"stock"] intValue] > 0) {
        ZPBrandDetailVC *detailVC = (ZPBrandDetailVC *)[self.storyboard instantiateViewControllerWithIdentifier:@"ZPBrandDetailVC"];
        detailVC.productId = itemDict[@"ProductId"];
        detailVC.listId = listID;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
    
}

#pragma  mark UIScrollView Delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    if (scrollView.contentOffset.y < 0) {
        [headerView egoRefreshScrollViewDidScroll:scrollView];
//    } else {
//        [footerView egoRefreshScrollViewDidScroll:scrollView];
//    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
//    if (isRefresh) {
        [headerView egoRefreshScrollViewDidEndDragging:scrollView];
//    }
    
//    [footerView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark EGORefresHeaderView Delegate
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view {
    return isRefresh;
}
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view {
    return [NSDate date];
}
-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view {
    isRefresh = YES;
    [self performSelector:@selector(requestDataFromNet) withObject:nil afterDelay:0];
}
#pragma mark EGORefreshFooterView Delegate
-(BOOL)egoRefreshTableFooterDataSourceIsLoading:(EGORefreshTableFooterView *)view {
    return isLoadingMore;
}
-(NSDate *)egoRefreshTableFooterDataSourceLastUpdated:(EGORefreshTableFooterView *)view {
    return [NSDate date];
}
-(void)egoRefreshTableFooterDidTriggerRefresh:(EGORefreshTableFooterView *)view {
    isLoadingMore = YES;
//    [self performSelector:@selector(requestDataFromNet) withObject:nil afterDelay:0];
}


#pragma mark button clicked method
//personcenter 
-(void)rightBarbuttonItemClicked:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

- (IBAction)personCenterButtonClicked:(UIButton *)sender {
    MemberCenterViewController *pvc = (MemberCenterViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"MemberCenterViewController"];
    
    [self.navigationController pushViewController:pvc animated:YES];
}
- (IBAction)cartButtonClicked:(UIButton *)sender {
    if ([CheckLoginObject isLogin]) {
        CartViewController *cvc = (CartViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CartViewController"];
        
        [self.navigationController pushViewController:cvc animated:YES];
    } else {
        [self login];
    }
    
}
#pragma mark login
- (void)login{
    logOnViewController *loginVC = (logOnViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"logOnViewController"];
    UINavigationController *navigationVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
    
    navigationVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    navigationVC.navigationBar.tintColor = [UIColor blackColor];
    // present
    [self presentViewController:navigationVC animated:YES completion:nil];
}

- (IBAction)backToTopButtonClicked:(UIButton *)sender {
    [_productListCollectionView scrollRectToVisible:CGRectMake(0, 0, _productListCollectionView.frame.size.width, _productListCollectionView.frame.size.height) animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
